package com.sduept.nwld.dataserver.controller.distribute;

import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.model.core.SubControlArea;
import com.sduept.cim.model.core.Substation;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.manager.distribute.PersonAndEquipmentDistributeManger;
import com.sduept.nwld.dataserver.model.distribute.PersonAndEquipmentDistribute;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.permission.entity.DepartmentEntityBean;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.manager.DepartManager;
import com.sduept.permission.manager.PersonnelManager;
import com.sduept.utils.PingYinUtil;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.NodeUnselectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Named
@ViewScoped
public class PersonAndEquipmentDistributeController extends AbstractController {

	private static final long serialVersionUID = 6024043227748471256L;

	@Autowired
	private PersonnelManager pm;
	@Autowired
	private DepartManager dm;
	@Autowired
	private CimManager cimManger;
	@Autowired
	private SubstationLedgerManager stationLedgerM;
	@Autowired
	private PersonAndEquipmentDistributeManger distributeManger;
	
	private TreeNode areaRoot; //控制区域树
	private TreeNode areaSelectedNode;
	private TreeNode personRoot; // 组织机构树根节点
	private TreeNode orgSelectedNode;
	/**
	 * 新选择的管理人员列表
	 */
	private List<PersonnelEntityBean> selectedPersonList = new ArrayList<PersonnelEntityBean>();
	/**
	 * 已存在的管理人员列表
	 */
	private List<PersonnelEntityBean> existPersonList = new ArrayList<PersonnelEntityBean>();
	private SubControlArea selectSubCtrlArea = new SubControlArea();
	private List<SubControlArea> subControlAreas = new ArrayList<SubControlArea>();
	private List<Substation> subStations = new ArrayList<Substation>();
	private List<Substation> selectSubStations = new ArrayList<Substation>();
	
	private TreeNode[] selectedNodes;
	private String ctrlArea;
	
	private List<PersonAndEquipmentDistribute> ctrlDistributes = new ArrayList<PersonAndEquipmentDistribute>();
	private HashMap<String, PersonnelEntityBean> personMap = new HashMap<String, PersonnelEntityBean>();
	
	private String selectdStandVolLevel = "500"; //电压等级默认为500
	private List<String> standVoltageLevels = new ArrayList<String>();
	
	@PostConstruct
	public void init() {
		ctrlArea = "";
		subControlAreas = cimManger.findAllSubControlAreas();
		initAreaTree(subControlAreas);
		initOrgTree();
		initPersonnelMap();
		getStandVolLevels();
	}
	
	private void initPersonnelMap(){
		List<PersonnelEntityBean> pbs = pm.findAllPersons();
		for (PersonnelEntityBean p : pbs) {
			personMap.put(p.getId(),p);
		}
	}
	
	public void initAreaTree(List<SubControlArea> subControlAreas) {
		areaRoot = new LibTreeNode("Root", null);
		for (SubControlArea s : subControlAreas) {
			new LibTreeNode("subControlArea",s,areaRoot);
		}
	}
	
	/**
	 * 控制区域树选择
	 * @param event
	 */
	public void onNodeSelect(NodeSelectEvent event) {
		subStations.clear();
		areaSelectedNode = event.getTreeNode();
		selectSubCtrlArea = (SubControlArea) areaSelectedNode.getData();
		query();
	}
	
	public void query() {
		subStations = distributeManger.findSubstation(selectSubCtrlArea.getRdfId(), selectdStandVolLevel);
	}
	
	public void onNodeUnselect(NodeUnselectEvent event) {
	}

	public String getStationGovernor(String personnelId) {
		String governor = "";
		//为了减少数据库查询次数，页面处理效率，本次会话的人员预存到map
		PersonnelEntityBean person = personMap.get(personnelId);
		if(null != person) {
			governor = person.getName();
		}
		return governor;
	}
	
	public void removeGovernor(PersonAndEquipmentDistribute p){
		distributeManger.delete(p);
		addSuccessMessage("移除成功");
		
	}
	
	public List<PersonAndEquipmentDistribute> getStationDistribute(Substation station) {
		List<PersonAndEquipmentDistribute> list = distributeManger.getEquipmentDistributeByStationId(station.getId());
		return list;
	}
	/**
	 * 获取当前变电站的调管单位
	 */
	public String getDispatchUnit(String stationId) {
		SubstationLedger ledger = stationLedgerM.findSubstationLedger(stationId);
		if(null != ledger) {
			return ledger.getDispatchUnit();
		} else {
			return null;
		}
	}
	/**
	 * 获取当前变电站的运维单位
	 */
	public String getMaintenanceUnit(String stationId) {
		SubstationLedger ledger = stationLedgerM.findSubstationLedger(stationId);
		if(null != ledger) {
			return ledger.getMaintenanceUnit();
		} else {
			return null;
		}
	}
	/**
	 * 初始化组织机构树
	 */
	private void initOrgTree() {
		personRoot = new LibTreeNode("Root", null);
		List<DepartmentEntityBean> roots = dm.findRootDepts();
		for (DepartmentEntityBean s : roots) {
			TreeNode orgRoot = new LibTreeNode("dept", s, personRoot);
			List<DepartmentEntityBean> ds = dm.getDepartmentsByParent(s.getId()); // 默认展开一级
			for (DepartmentEntityBean d : ds) {
				new LibTreeNode("dept", d, orgRoot);
			}
			List<PersonnelEntityBean> ps = dm.findDeptPersonnels(s.getId());
			for (PersonnelEntityBean p : ps) {
				new DefaultTreeNode("personnel", p, orgRoot);
			}
			orgRoot.setExpanded(true);
		}
	}
	
	public void onOrgNodeSelect(NodeSelectEvent event) {
		orgSelectedNode = event.getTreeNode();
		if ("personnel".equals(orgSelectedNode.getType())) {
			PersonnelEntityBean selectedPerson = (PersonnelEntityBean) orgSelectedNode.getData();
			if(!selectedPersonList.contains(selectedPerson) && !existPersonList.contains(selectedPerson)) {
				selectedPersonList.add(selectedPerson);
			} else {
				alertErrorMessage("该人员已存在！");
			}
		}
	}
	
	public void onOrgNodeUnSelect(NodeUnselectEvent event) {
		orgSelectedNode = event.getTreeNode();
		if ("personnel".equals(orgSelectedNode.getType())) {
			PersonnelEntityBean selectedPerson = (PersonnelEntityBean) orgSelectedNode.getData();
			selectedPersonList.remove(selectedPerson);
		}
	}
	
	/**
	 * 组织机构树展开
	 * @param event
	 */
	public void onOrgNodeExpand(NodeExpandEvent event) {
		TreeNode node = event.getTreeNode();
		DepartmentEntityBean dept = (DepartmentEntityBean) node.getData();
		List<DepartmentEntityBean> ds = dm.getDepartmentsByParent(dept.getId());
		for (DepartmentEntityBean d : ds) {
			new LibTreeNode("dept", d, node);
		}
		List<PersonnelEntityBean> personnels = dm.findDeptPersonnels(dept.getId());
		if (personnels != null && personnels.size() > 0) {
			for (PersonnelEntityBean p : personnels) {
				new DefaultTreeNode("personnel", p, node);
			}
		}
	}
	
	/**
	 * 管控区域树展开
	 * @param event
	 */
	public void onNodeExpand(NodeExpandEvent event) {
		TreeNode node = event.getTreeNode();
		if("subControlArea".equals(node.getType())) {
			selectSubCtrlArea = (SubControlArea) node.getData();
			List<Substation> substations = cimManger.findSubstationByRdfId(selectSubCtrlArea.getRdfId());
			for (Substation substation : substations) {
				new LibTreeNode("station", substation, node);
			}
		}
	}
	
	public void preDistribute() {
		selectedPersonList.clear();
		existPersonList.clear();
		getExistGover();
	}

	private void getExistGover() {
		if(selectSubStations.size() == 1) {
			Substation station = selectSubStations.get(0);
			List<PersonAndEquipmentDistribute> distributeList = distributeManger.getEquipmentDistributeByStationId(station.getId());
			for (PersonAndEquipmentDistribute dist : distributeList) {
				PersonnelEntityBean per = pm.findPersonnelById(dist.getPersonId());
				existPersonList.add(per);
			}
		}
	}
	public void save(){
		for(Substation station : selectSubStations) {
			List<PersonnelEntityBean> govers = distributeManger.getGovernorBySubstationId(station.getId());
			for (PersonnelEntityBean person : selectedPersonList) {
				if(!govers.contains(person)) {
					PersonAndEquipmentDistribute distribute = new PersonAndEquipmentDistribute();
					distribute.setEquipmentId(station.getId());
					distribute.setEquipmentName(station.getName());
					distribute.setPersonId(person.getId());
					distribute = distributeManger.createOrUpdate(distribute);
				}
			}
		}
		addSuccessMessage("管理者配置成功！");
		selectSubStations.clear();
	}
	
	public void delete() {
		for(Substation station : selectSubStations) {
			List<PersonAndEquipmentDistribute> list = distributeManger.getEquipmentDistributeByStationId(station.getId());
			if (list.size()>0) {
				for (PersonAndEquipmentDistribute personAndEquipmentDistribute : list) {
					distributeManger.delete(personAndEquipmentDistribute);
				}
			}
		}
		selectSubStations.clear();
		addSuccessMessage("移除成功！");
	}
	
	public List<String> completeCtrlArea(String query) {
		List<String> qualifiedEquipmentNames = new ArrayList<String>();
        for (SubControlArea area : subControlAreas) {
        	String pName = PingYinUtil.getPingYinHeader(area.getName());
        	if (pName.contains(query)) {
        		qualifiedEquipmentNames.add(area.getName());
        	}
        }
		return qualifiedEquipmentNames;
	}
	
	public List<String> completeStationName(String query) {
		List<String> qualifiedEquipmentNames = new ArrayList<String>();
        for (Substation station : subStations) {
        	String pName = PingYinUtil.getPingYinHeader(station.getName());
        	if (pName.contains(query)) {
        		qualifiedEquipmentNames.add(station.getName());
        	}
        }
		return qualifiedEquipmentNames;
	}
	
	/**
	 * 获取标准电压等级
	 */
	private void getStandVolLevels() {
		List<Float> vols = cimManger.findStationStandVolLevels();
		for (Float vol : vols) {
			String volStr = String.valueOf(vol);
			volStr = volStr.replace(".0", "");
			standVoltageLevels.add(volStr);
		}
	}
	
	public void autoComplete(SelectEvent event) {
		Object item = event.getObject();
		if (null != item) {
			filterTree(item.toString());
		}
	}
	
	private void filterTree(String name) {
		areaRoot = new DefaultTreeNode();
		List<SubControlArea> subControlAreas = cimManger.findsubControlAreasByName(name);
		initAreaTree(subControlAreas);
	}
	
	public void removeSelectPerson(PersonnelEntityBean bean) {
		selectedPersonList.remove(bean);
	}

	public List<Substation> getSubStations() {
		return subStations;
	}

	public void setSubStations(List<Substation> subStations) {
		this.subStations = subStations;
	}

	public List<Substation> getSelectSubStations() {
		return selectSubStations;
	}

	public void setSelectSubStations(List<Substation> selectSubStations) {
		this.selectSubStations = selectSubStations;
	}

	public TreeNode getPersonRoot() {
		return personRoot;
	}

	public void setPersonRoot(TreeNode personRoot) {
		this.personRoot = personRoot;
	}

	public TreeNode getAreaRoot() {
		return areaRoot;
	}

	public void setAreaRoot(TreeNode areaRoot) {
		this.areaRoot = areaRoot;
	}

	public String getCtrlArea() {
		return ctrlArea;
	}

	public void setCtrlArea(String ctrlArea) {
		this.ctrlArea = ctrlArea;
	}

	public List<PersonAndEquipmentDistribute> getCtrlDistributes() {
		return ctrlDistributes;
	}

	public void setCtrlDistributes(
			List<PersonAndEquipmentDistribute> ctrlDistributes) {
		this.ctrlDistributes = ctrlDistributes;
	}

	public TreeNode[] getSelectedNodes() {
		return selectedNodes;
	}

	public void setSelectedNodes(TreeNode[] selectedNodes) {
		this.selectedNodes = selectedNodes;
	}

	public String getSelectdStandVolLevel() {
		return selectdStandVolLevel;
	}

	public void setSelectdStandVolLevel(String selectdStandVolLevel) {
		this.selectdStandVolLevel = selectdStandVolLevel;
	}

	public List<String> getStandVoltageLevels() {
		return standVoltageLevels;
	}

	public void setStandVoltageLevels(List<String> standVoltageLevels) {
		this.standVoltageLevels = standVoltageLevels;
	}

	public List<PersonnelEntityBean> getSelectedPersonList() {
		return selectedPersonList;
	}

	public void setSelectedPersonList(List<PersonnelEntityBean> selectedPersonList) {
		this.selectedPersonList = selectedPersonList;
	}

	public List<PersonnelEntityBean> getExistPersonList() {
		return existPersonList;
	}

	public void setExistPersonList(List<PersonnelEntityBean> existPersonList) {
		this.existPersonList = existPersonList;
	}

}
